package com.tool4j.util.security;

import com.tool4j.util.JwtUtil;
import com.tool4j.util.UserPermission;
import com.tool4j.util.http.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.net.InetSocketAddress;

@Component
@Slf4j
public class AuthUtil {

    @Autowired
    private IPUtil ipUtil;

    /**
     * 验证请求是否合法（JWT Token 验证）
     * 成功则将用户信息放入 Reactor Context，并返回 Mono.just(true)
     * 失败则返回错误 Mono
     */
    public boolean verify(ServerWebExchange exchange) {
        if (UserPermission.get(exchange) != null) {
            return true;
        }
        var request = exchange.getRequest();
        String uri = request.getURI().getPath();
        // 获取远程地址
        InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
        String ip = remoteAddress != null ? remoteAddress.getAddress().getHostAddress() : "unknown";
        String region = ipUtil.searchRegion(ip);
        String token;
        String authHeader = request.getHeaders().getFirst("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else {
            return false;
        }
        Long userId = JwtUtil.verify(token);
        UserPermission.UserInfo userInfo = new UserPermission.UserInfo()
                .setUserId(userId)
                .setToken(token)
                .setIp(ip)
                .setRegion(region);

        // 4. 尝试刷新 token（可选）
        String refreshToken = JwtUtil.refreshToken(token, userId);
        if (refreshToken != null) {
            userInfo.setToken(refreshToken);
            // 可以设置响应头返回新 token
            exchange.getResponse().getHeaders().set("token", refreshToken);
        }
        // 5. 将用户信息存入 Reactor Context
        exchange.getAttributes().put(UserPermission.ATTRIBUTE_KEY, userInfo);
        return true;
    }
}